/*********************************************************************************
 *      Copyright:  (C) 2022 Zhang Changxing<ZhangChangxingVIP@163.com>
 *                  All rights reserved.
 *
 *       Filename:  databse.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/14/2022)
 *         Author:  Zhang Changxing <ZhangChangxingVIP@163.com>
 *      ChangeLog:  1, Release initial version on "04/14/2022 09:34:49 PM"
 *                 
 ********************************************************************************/
#include "database.h"

sqlite3 			*db;

/*Database initialization, open the database*/
int  sqlite_init(char *dbname)
{
	int rc =-1;
	char dbname_buf[64];

	if(NULL == dbname)
	{
		log_error("The sqlite_init() argument incorrect!\n");
	}

	sprintf(dbname_buf, "../database/%s.db", dbname);
	rc = sqlite3_open(dbname_buf, &db);
	if (rc)
	{
		log_error("Can't open database:%s\n", sqlite3_errmsg(db));
		return -1;
	}
	else
	{
		log_debug("Opened database successfully\n");
		return 0;
	}
}

/* create a table */
int sqlite_create_table(char *table_name)
{
	char 	sql[100];
	int 	rc =-1;
	char 	*zErrMsg = 0;

	if(NULL == table_name)
	{
		log_error("The sqlite_create_table() argument incorrect!\n");
	}

	sprintf(sql, "CREATE TABLE if not exists %s(SN CHAR(10),DATIME CHAR(50),TEMPERATURE CHAR(10));", table_name);
	rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
	
	if (rc != SQLITE_OK)
	{
		log_error("Sqlite_create_table failure:%s\n", zErrMsg);
		sqlite3_free(zErrMsg);
		return -1;
	}

	log_debug("Open table[%s] created successfully!\n", table_name);
	return 0;
}

/* Insert data into a table */
int data_insert(pack_info_t pack_info, char *table_name)
{
	char 	sql[512];
	int 	rc =-1;
	char 	*zErrMsg = 0;

	if(NULL == table_name)
	{
		log_error("The data_insert() argument incorrect!\n");
	}

	sprintf(sql, "INSERT INTO %s VALUES ('%s', '%s', '%f');" ,\
	table_name, pack_info.devid, pack_info.strtime, pack_info.temper);
	log_debug("data insert sql:%s\n", sql);
	rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
   	if ( rc != SQLITE_OK )
	{
      	log_error("Sqlite_insert: %s\n", zErrMsg);
      	sqlite3_free(zErrMsg);
		return -1;
   	}

    log_info("Last data insert table successfully:device name:%s, date time:%s, temperature:%f\n", \
	pack_info.devid, pack_info.strtime, pack_info.temper);
	return 0;
}

int close_database(void)
{
	int rc = sqlite3_close(db);

	while ( rc == SQLITE_BUSY)
	{
		// set rc to something that will exit the while loop
		rc = SQLITE_OK;
		sqlite3_stmt * stmt = sqlite3_next_stmt(db, NULL);

		if (stmt != NULL)
		{
			rc = sqlite3_finalize(stmt);
			if (rc == SQLITE_OK)
			{
				rc = sqlite3_close(db);
			}
		}
	}

	log_debug("Close database ucessfully!\n");
	return 0;
}

